import React, { useState, useMemo, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";

// 组件引入
import HomeHeader from "../components/Home/HomeHeader";
import NewsItem from "../components/Home/NewsItem";

import dayjs from "dayjs";
import actions from "../store/action";
import api from "../api";
import "./styles/Home.scss";
// antd
import { Swiper, Divider, DotLoading } from "antd-mobile";

function Home(props) {
  // 创建所需要的状态
  const dateMonthMap = {
    1: "一月",
    2: "二月",
    3: "三月",
    4: "四月",
    5: "五月",
    6: "六月",
    7: "七月",
    8: "八月",
    9: "九月",
    10: "十月",
    11: "十一月",
    12: "十二月",
  };
  const navigate = useNavigate();
  const [today, setToday] = useState(dayjs().format("YYYYMMDD"));
  const [month, setMonth] = useState(null);
  const [day, setDay] = useState(null);
  const [bannerData, setBannerData] = useState([]);
  const [newsList, setNewsList] = useState([]);
  useMemo(() => {
    setMonth(dateMonthMap[dayjs(today).month() + 1]);
    setDay(dayjs(today).date());
  }, [today]);

  useMemo(() => {});
  async function getPageHomeInfo() {
    const { stories, top_stories, date } = await api.queryNewsLatest();
    setBannerData(top_stories);
    newsList.push({
      stories,
      date,
    });
    setNewsList([...newsList]);
  }
  useEffect(() => {
    getPageHomeInfo();
  }, []);

  function onConfirm(date) {
    console.log(date);
    setToday(dayjs(date).format("YYYYMMDD"));
  }
  // 点击swiper跳转detail页面
  function handlerRoute(id) {
    navigate("/detail?id=" + id);
  }

  // 监听触底
  const loadMore = useRef();
  useEffect(() => {
    // 试图触底加载跟过 逻辑是根据绑定试图是否显示 如果显示则代表触底
    let ob = new IntersectionObserver(async (entries) => {
      const { intersectionRatio } = entries[0];
      console.log(intersectionRatio, "isIntersecting");
      // intersectionRatio = 0 标识在试图外
      if (intersectionRatio) {
        try {
          let time = newsList[newsList.length - 1]["date"];
          const result = await api.queryNewsBefore(time);
          newsList.push(result);
          setNewsList([...newsList]);
        } catch (error) {
          console.log(error);
        }
      }
    });
    const loadingRef = loadMore.current;
    ob.observe(loadingRef);

    return () => {
      // 销毁
      console.log("销毁？");
      ob.unobserve(loadingRef); //loadMore.current=null
      ob = null;
    };
  }, []);

  return (
    <div className="home-container">
      <HomeHeader today={today} month={month} day={day} onConfirm={onConfirm} />
      {/* 轮播图 */}
      <div className="swipe">
        {bannerData.length ? (
          <Swiper autoplayInterval={4000} loop autoplay>
            {bannerData.map((item) => {
              const { id, image, title, hint } = item;
              return (
                <Swiper.Item key={id}>
                  <div className="swipe-item" onClick={() => handlerRoute(id)}>
                    <img src={image} />
                    <div className="desc">
                      <div className="title">{title}</div>
                      <div className="author">{hint}</div>
                    </div>
                  </div>
                </Swiper.Item>
              );
            })}
          </Swiper>
        ) : null}
      </div>
      {/* 新闻列表 */}
      <div className="news-list-content">
        {newsList.length !== 0 &&
          newsList.map((item, index) => {
            const { date, stories } = item;
            return (
              <div className="news-box" key={index}>
                {index !== 0 ? (
                  <Divider contentPosition="left" key={date}>
                    {dayjs(date).format("MM月DD日")}
                  </Divider>
                ) : null}
                <div className="list">
                  {stories.length
                    ? stories.map((item) => {
                        return <NewsItem item={item} key={item.id} />;
                      })
                    : null}
                </div>
              </div>
            );
          })}
      </div>

      {/* 触底 */}
      <div
        className="loading"
        ref={loadMore}
        style={{
          display: newsList.length === 0 ? "none" : "block",
        }}
      >
        <DotLoading />
      </div>
    </div>
  );
}

export default Home;
